<template>
  <CommonPage show-footer :show-header="false">
    <!-- <div class="flex flex-rr mb-10">
      <div class="mr-10">
        <n-upload accept=".xls, .xlsx" :show-file-list="false" :max="1">
          <n-button type="primary">
            <TheIcon icon="uil:upload" :size="18" class="mr-5" />
            导入
          </n-button>
        </n-upload>
      </div>
    </div> -->

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :columns="columns"
      :get-data="api.getUserList"
    >
      <template #queryBar>
        <QueryBarItem label="姓名" :label-width="90">
          <n-input
            type="text"
            clearable
            placeholder="请输入姓名"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.name"
          />
        </QueryBarItem>
        <QueryBarItem label="年龄" :label-width="90">
          <div class="flex flex-cc">
            <n-input-number
              clearable
              placeholder=""
              @keydown.enter="$table?.handleSearch"
              v-model:value="queryItems.minAge"
            />
            <div class="ml-5 mr-5">至</div>
            <n-input-number
              clearable
              placeholder=""
              @keydown.enter="$table?.handleSearch"
              v-model:value="queryItems.maxAge"
            />
          </div>
        </QueryBarItem>
        <QueryBarItem label="身份证" :label-width="90">
          <n-input
            type="text"
            clearable
            placeholder="请输入身份证"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.idcard"
          />
        </QueryBarItem>
        <QueryBarItem label="残疾人证编号" :label-width="90">
          <n-input
            type="text"
            clearable
            placeholder="请输入残疾人证编号"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.disabilityIdCard"
          />
        </QueryBarItem>
        <QueryBarItem label="性别" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="全部"
            :options="getOptions('GENDER')"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.gender"
          />
        </QueryBarItem>
        <QueryBarItem label="居委" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="全部"
            :options="juweiList"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.community"
          />
        </QueryBarItem>
        <!-- <QueryBarItem label="有效性" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="全部"
            :options="getOptions('dataStatus')"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.dataStatus"
          />
        </QueryBarItem> -->
        <QueryBarItem label="数据状态" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="全部"
            :options="getOptions('movingInOutStatus')"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.movingInOutStatus"
          />
        </QueryBarItem>
        <QueryBarItem label="残疾类别" :label-width="90">
          <n-cascader
            multiple
            clearable
            placeholder="请选择残疾信息"
            showPath
            check-strategy="child"
            :options="getOptions('disabilityCategory', 'level')"
            v-model:value="queryItems.disabilityInfoList"
          />
        </QueryBarItem>
        <QueryBarItem label="补贴领取情况" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="全部"
            :options="getOptions('subsidyType')"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.subsidyType"
          />
        </QueryBarItem>
        <!-- v-model:value="queryItems.receivedSubsidyList" -->
        <QueryBarItem label="补贴类型" :label-width="90">
          <n-cascader
            multiple
            clearable
            placeholder="请选择补贴类型"
            showPath
            check-strategy="child"
            :options="getOptions('subsidySituation')"
            v-model:value="queryItems.receivedSubsidyList"
          />
        </QueryBarItem>
        <QueryBarItem label="标签" :label-width="90">
          <n-cascader
            multiple
            clearable
            placeholder="请选择用户标签"
            showPath
            check-strategy="child"
            :options="getOptions('tag')"
            v-model:value="queryItems.tagList"
          />
        </QueryBarItem>
        
        <QueryBarItem label="街道" :label-width="90">
          <n-select
            clearable
            filterable
            placeholder="请选择街道"
            :options="streetList"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.streetList"
          />
        </QueryBarItem>
      </template>

      <template #title-right>
        <div class="flex">
          <n-upload
            class="mr-10"
            name="file"
            accept=".xls, .xlsx"
            :show-file-list="false"
            :action="`${baseUploadUrl}${uploadUrl}`"
            :headers="{
              Authorization: 'Bearer ' + getToken(),
            }"
            @before-upload="onBeforeUpload"
            @finish="onUploadFinish"
            @error="onUploadError"
          >
            <n-button type="primary" size="small">
              <TheIcon icon="material-symbols:upload" :size="18" class="mr-5" />
              上传
            </n-button>
          </n-upload>

          <n-button type="primary" size="small" secondary @click="exportExcel">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />
            下载
          </n-button>
        </div>
      </template>
    </CrudTable>

    <!-- 上传结果 -->
    <n-modal
      style="width: 500px"
      preset="dialog"
      :show-icon="false"
      v-model:show="uploadResultVisible"
    >
      <n-result
        :title="uploadResult.status === 'success' ? '导入成功' : '导入失败'"
        :status="uploadResult.status"
      >
        <!-- 成功 -->
        <div class="ta-center" v-if="uploadResult.status === 'success'">
          <div v-if="props.refresh">
            <div
              class="cl-success"
              v-html="uploadResult.postCount.replace(/\//g, '<br />')"
            ></div>
          </div>

          <div v-else>
            <span>新增数量：</span>
            <span class="cl-success">{{ uploadResult.postCount || 0 }}</span>
            <span>，</span>
            <span>更新数量：</span>
            <span class="cl-primary">{{ uploadResult.putCount || 0 }}</span>
            <span></span>
          </div>
        </div>

        <!-- 失败 -->
        <div v-else>
          <div class="fw-bold fz-15 mb-15">您提交的内容有如下错误：</div>

          <n-input
            type="textarea"
            placeholder=""
            readonly
            :rows="5"
            :value="uploadResult.errors?.join('\n')"
          ></n-input>
        </div>

        <template #footer>
          <n-button
            style="width: 200px"
            size="large"
            @click="copy"
            v-if="uploadResult.status === 'error'"
          >
            复制错误信息
          </n-button>
        </template>
      </n-result>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { h, onMounted, ref } from 'vue'
import { NButton } from 'naive-ui'
import { renderIcon, getOptions, getToken } from '@/utils'
import api from './api'

const $table = ref(null)
const router = useRouter()
const queryItems = ref({
  dataStatus: null,
  gender: null,
  community: null,
  disabilityInfoList: [],
  subsidyType: null,
  receivedSubsidyList: null,
  streetList: null,
  tagList: null,
})
const extraParams = ref({})

// 上传结果
const uploadResult = ref({})
const uploadResultVisible = ref(false)

// 导入
const baseUploadUrl = ''
const uploadUrl = '/api/sys/peoplebaseinfo/import'

const columns = [
  {
    title: 'Id',
    key: 'id',
    width: 220,
  },
  {
    title: '姓名',
    key: 'name',
    width: 100,
  },
  {
    title: '性别',
    key: 'gender',
    width: 100,
  },
  {
    title: '身份证',
    key: 'idCard',
    width: 200,
  },
  {
    title: '残疾类别',
    key: 'disabilityLevel',
    width: 200,
  },
  {
    title: '居委',
    key: 'neighborhoodCommittee',
    width: 150,
  },
  {
    title: '地址',
    key: 'address',
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            secondary: true,
            onClick: () =>
              router.push(`/user/detail?id=${row.id}&idCard=${row.idCard}`),
          },
          {
            default: () => '查看',
            icon: renderIcon('ph:eye', { size: 14 }),
          }
        ),
      ]
    },
  },
]

// 居委列表
const juweiList = ref([])
const streetList = ref([])

onMounted(() => {
  getJuweiList()
  getStreetList()
  $table.value?.handleQuery()
})

// 获取居委下拉列表
async function getJuweiList() {
  const { code, data } = await api.getJuweiList()

  if (code === 200) {
    const list = data.map((v) => {
      return {
        label: v,
        value: v,
      }
    })

    juweiList.value = list
  }
}

// 获取街道下拉列表
async function getStreetList() {
  const { code, data } = await api.getStreetList()

  if (code === 200) {
    const list = data.map((v) => {
      return {
        label: v.name,
        value: v.name,
      }
    })

    streetList.value = list
  }
}

// 导入前
function onBeforeUpload() {
  $message.loading('正在导入...')
}

// 导入成功
function onUploadFinish(e) {
  const { code, msg } = JSON.parse(e.event.target.responseText)

  if (code === 200) {
    $message.success('导入成功')
    $table.value?.handleQuery()
  } else {
    $message.error(msg || '上传失败')
  }
}

// 导入失败
function onUploadError(e) {
  const { msg } = JSON.parse(e.event.target.responseText)
  $message.error(msg || '上传失败')
}

// 导出
function exportExcel() {
  window.open('/api/sys/peoplebaseinfo/export')
}
</script>

<style lang="scss" scoped>
:deep(.n-card) {
  border: none !important;
}

:deep(.n-card__content) {
  padding: 0 !important;
  background-color: #f5f6fb !important;
}
</style>
